#ifndef QCONNECTIONPOOLMUTI_H
#define QCONNECTIONPOOLMUTI_H
#include <QtSql>
#include <QQueue>
#include "qconnectionpool.h"

class QConnectionPoolMuti
{
public:
    QConnectionPoolMuti(void)
    {}
    ~QConnectionPoolMuti(void)
    {
        QMap<int, QConnectionPool*>::iterator it = m_mapPool.begin();
        while (it != m_mapPool.end())
        {
            it.value()->release();
            it++;
        }
        m_mapPool.clear();
    }
public:
    QMap<int, QConnectionPool*> m_mapPool;
    QConnectionPool* GetPool(int nId = 0)
    {
        QMutexLocker locker(&mutex);
        QMap<int, QConnectionPool*>::iterator it = m_mapPool.find(nId);
        if (it == m_mapPool.end())
        {
            locker.unlock();
            return CreatePool(nId);
        }
        return it.value();
    }
    QConnectionPool* CreatePool(int nId)
    {
        QMutexLocker locker(&mutex);
        QConnectionPool* pPool = new QConnectionPool(nId);
        m_mapPool[nId] = pPool;
        return pPool;
    }
    void ReleasePool(int nId)
    {
        QMutexLocker locker(&mutex);
        QConnectionPool* pool = GetPool(nId);
        if (pool == nullptr)
        {
            return;
        }
        pool->release();
        QMap<int, QConnectionPool*>::iterator it = m_mapPool.find(nId);
        if (it != m_mapPool.end())
        {
            m_mapPool.erase(it);
        }
        return;
    }

    static QConnectionPoolMuti &Instance()
    {
        static QConnectionPoolMuti Instance;
        return Instance;
    }

    QConnectionPoolMuti &ConnectionPoolMuti()
    {
        return QConnectionPoolMuti::Instance();
    }

    QConnectionPool* ConnectionPool(int nId = 0)
    {
        return ConnectionPoolMuti().GetPool(nId);
    }

private:
    QMutex mutex;
};

#endif // QCONNECTIONPOOLMUTI_H

